from flask import Blueprint, json,request,jsonify
import random
from rediscon import r 
from db import db1
from werkzeug.security import generate_password_hash,check_password_hash

bp_user = Blueprint('user',__name__)

@bp_user.route('smscode')
def smscode():
    mobile = request.args.get('mobile')
    code = str(random.randint(10000,99999))
    r.set_str(mobile,code,60)
    return jsonify({'code':200,'scode':code})


@bp_user.route('userM',methods=['POST'])
def userM():
    data = request.data
    if data:
        data= json.loads(data)
    else:
        data = request.form
    code = r.get_str(data['mobile'])
    if not code:
        return jsonify({'code':10016,'mes':'验证码过期'})
    if code != data['code']:
        return jsonify({'code':10017,'mes':'验证码不存在'})
    # 验证手机号
    sql = "select id from user where mobile='%s'"%(data['mobile'])
    res= db1.insert(sql)
    if res:
        return jsonify({'code':200,'mes':'手机号已经存在，不能注册了'})
    # 把手机号写入到数据库中
    sql =  "insert into user value(0,'%s','%s')"%(data['mobile'],generate_password_hash(data['password']))
    db1.insert(sql)
    return jsonify({'code':200})

@bp_user.route('/login',methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(request.data)
    else:
        data= request.form
    sql = "select * from user where mobile='%s'"%(data['mobile'])
    res = db1.findone(sql)
    #假如存在比对密码
    if res:
        if check_password_hash(res['password'],data['password']):
            #密码正确返回id,mobile
            return jsonify({'code':200,'id':res['id'],'mobile':res['mobile']})
        else:
             return jsonify({'code':10016,'mes':'密码错误'})
    else:
        return jsonify({'code':10017,'mes':'用户不存在'})

@bp_user.route('/userlist')
def userlist():
    sql = "select * from user order by id desc"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})